/*
 @desc: 用户中心
 @date: 2021/12/28
 */

#import "UserViewController.h"
#import "UserTableViewCell.h"
#import "UserViewModel.h"

NSString * const user_cell = @"user_cell";

@interface UserViewController ()

@property(nonatomic,strong)UserViewModel * mViewModel;

@end

@implementation UserViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self configureTableView];
    [self.mViewModel begin:^{
        [self.mTableView reloadData];
    }];
}
//MARK: UITableViewDataSource UITableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [self.mViewModel sectionCount];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return  [self.mViewModel cellCountFor:section];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UserTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:user_cell forIndexPath:indexPath];
    UserBean * bean = [self.mViewModel fetchCellDataWith:indexPath];
    [cell setData:bean];
    return  cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UserBean * bean = [self.mViewModel fetchCellDataWith:indexPath];
    if (bean.url != nil) {
        NSURL * url = [[NSURL alloc] initWithString: bean.url];
        BOOL flag = [[UIApplication sharedApplication] canOpenURL:url];
        if (flag) {
            [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
        }
    }
}

//MARK: 基础配置
-(void )configureTableView {
    UINib * nib = [UINib nibWithNibName:@"UserTableViewCell" bundle:[NSBundle mainBundle]];
    [_mTableView registerNib:nib forCellReuseIdentifier:user_cell];
    _mTableView.rowHeight = 44;
}

//MARK: 懒加载
-(UserViewModel *)mViewModel {
    if (_mViewModel == nil) {
        _mViewModel = [UserViewModel new];
    }
    return _mViewModel;
}
@end
